<script setup>
import { onMounted, ref, watch } from 'vue'
import { withBase } from 'vitepress'

const props = defineProps({
  url: {
    type: String,
    required: true
  }
})

const SwaggerUIContainer = ref(null)
const isLoaded = ref(false)
const basePath = ref('')

onMounted(async () => {
  // 动态导入Swagger UI
  const { SwaggerUIBundle } = await import('swagger-ui-dist')
  
  if (SwaggerUIContainer.value) {
    basePath.value = window.location.pathname.split('/').slice(0, -2).join('/') || '/'
    const specUrl = withBase(props.url)
    
    SwaggerUIBundle({
      url: specUrl,
      dom_id: '#swagger-ui-container',
      deepLinking: true,
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIBundle.SwaggerUIStandalonePreset
      ],
      layout: 'BaseLayout',
      docExpansion: 'list',
      persistAuthorization: true,
      displayOperationId: false,
      filter: true,
    })
    
    // 加载CSS
    loadCSS()
    isLoaded.value = true
  }
})

const loadCSS = () => {
  const link = document.createElement('link')
  link.rel = 'stylesheet'
  link.href = withBase('/swagger-ui.css')
  document.head.appendChild(link)
}
</script>

<template>
  <div>
    <div v-if="!isLoaded" class="swagger-loading">
      <p>加载API文档中...</p>
    </div>
    <div id="swagger-ui-container" ref="SwaggerUIContainer"></div>
  </div>
</template>

<style>
.swagger-loading {
  padding: 20px;
  text-align: center;
  font-size: 1.2em;
}

/* 覆盖Swagger UI样式以适应VitePress */
:root.dark #swagger-ui-container {
  filter: invert(0.85) hue-rotate(180deg);
}

:root.dark #swagger-ui-container pre {
  filter: invert(0.85) hue-rotate(180deg);
}

:root.dark #swagger-ui-container .highlight-code {
  filter: invert(0.85) hue-rotate(180deg);
}

#swagger-ui-container .swagger-ui {
  margin-top: 20px;
}

#swagger-ui-container .swagger-ui .info {
  margin-bottom: 30px;
}
</style> 